import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: {},
    allChecked: false,
  },
  mutations: {
    addCartItem(state, nv) {
      let tempCart = state.cartList;
      if (tempCart[nv.tradeItemId]) {
        nv.count += 1;
        tempCart[nv.tradeItemId] = nv;
      } else {
        nv.count = 1; // 为对象添加一个初始化的数量
        tempCart[nv.tradeItemId] = nv;
      }
      state.cartList = [];
      state.cartList = tempCart;
    },
    addCartCount(state, key){
      let tempCart = state.cartList;
      tempCart[key].count += 1;
      state.cartList = [];
      state.cartList = tempCart;
    },
    subCartCount(state, key){
      let tempCart = state.cartList;
      let num = tempCart[key].count -1;
      if(num==0){
        delete tempCart[key]
      }else{
        tempCart[key].count = num;
      }
      state.cartList = [];
      state.cartList = tempCart;
    },
    deleteCartCount(state, key){
      // 编辑的右侧小删除按钮
      let tempCart = state.cartList;
      delete tempCart[key];
      state.cartList = [];
      state.cartList = tempCart;
    },
    chooseAll(state,flag){
      let tempCart = state.cartList;
        // console.log("1")
        for(let key in tempCart){
          if(flag){
            tempCart[key].flag = true;
          }else{
            tempCart[key].flag = false;
          }
        }
      state.cartList = [];
      state.cartList = tempCart;
    },
    checkItem(state,key){
      let arr = Object.values(state.cartList);
      if(key){
        state.cartList[key].flag = !state.cartList[key].flag;
        arr.forEach((value)=>{
          if(!value.flag){
            state.allChecked = false;
            return;
          }
        })
      }else{
        state.allChecked = (arr.length > 0);
        arr.forEach((v)=>{
          if(!v.flag){
            state.allChecked = false;
            return;
          }
        })
      }
    },
    removeItem(state){
      let arr = Object.keys(state.cartList);
      arr.forEach((v)=>{
        if(state.cartList[v].flag){
          Vue.delete(state.cartList,v);
        }
      });
      this.commit("checkItem")
    }
  },
  actions: {
  },
  modules: {
  }
})
